package pro3;

import java.io.IOException;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet("/Ans1/LoginServlet")
public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");

        String email = request.getParameter("email");
        String password = request.getParameter("password");

        System.out.println("登录请求收到");
        System.out.println("邮箱：" + email);
        System.out.println("密码：" + password);

        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            Connection conn = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/cwl_db", "root", "123456"
            );

            PreparedStatement stmt = conn.prepareStatement("SELECT * FROM cwl_user WHERE email = ? AND password = ?");
            stmt.setString(1, email);
            stmt.setString(2, password);

            ResultSet rs = stmt.executeQuery();

            if (rs.next()) {
                HttpSession session = request.getSession();
                session.setAttribute("email", email);

                response.sendRedirect("index.jsp");
            } else {
                request.setAttribute("error", "邮箱或密码错误");
                request.getRequestDispatcher("login.jsp").forward(request, response);
            }

            rs.close();
            stmt.close();
            conn.close();

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            System.err.println("MySQL JDBC 驱动未找到！");
            request.setAttribute("error", "MySQL JDBC 驱动未找到");
            request.getRequestDispatcher("/Ans1/login.jsp").forward(request, response);
        } catch (SQLException e) {
            e.printStackTrace();
            System.err.println("数据库连接失败！");
            request.setAttribute("error", "数据库连接失败");
            request.getRequestDispatcher("/Ans1/login.jsp").forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "系统错误，请重试");
            request.getRequestDispatcher("/Ans1/login.jsp").forward(request, response);
        }
    }
}
